package docs;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import libaray.File;
import libaray.Utils;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

/**
 * Servlet Filter implementation class SupperCacheFilter
 */

public class SupperCacheFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public SupperCacheFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rsp = (HttpServletResponse) response;
		
		rsp.setContentType("text/html");

		String url = req.getRequestURI();
		
		if(req.getQueryString()!=null)
		{
			url += "?" + req.getQueryString();
		} 
		
		System.out.println(url);

		String file = "/index.jsp";
		if(Pattern.matches("[\\/]{1}questions[\\/]{1}tagged[\\/]{1}[\\w\\W]+$", url))
		{
			file = "/tag.jsp";
		}
		if(Pattern.matches("[\\/]{1}users[\\/]{1}[\\w\\W]+$", url))
		{
			file = "/users.jsp";
		}
		if(url.equals("/"))
		{
			file = "/home.jsp";
			
			String redirectURL = rsp.encodeRedirectURL(file);
	   		
	   		RequestDispatcher dispatcher = req.getRequestDispatcher(redirectURL);
	   		BufferedHttpResponseWrapper wrapper = new BufferedHttpResponseWrapper(rsp);
	   		
	   		dispatcher.include(request, wrapper);
	   		String wrapperContent = new String(wrapper.getOutput());
	   		rsp.getWriter().println(wrapperContent);
	   		return;
		}
		if(url.equals("/privacy-policy.jsp"))
		{
			file = "/privacy-policy.jsp";
			
			String redirectURL = rsp.encodeRedirectURL(file);
	   		
	   		RequestDispatcher dispatcher = req.getRequestDispatcher(redirectURL);
	   		BufferedHttpResponseWrapper wrapper = new BufferedHttpResponseWrapper(rsp);
	   		
	   		dispatcher.include(request, wrapper);
	   		String wrapperContent = new String(wrapper.getOutput());
	   		rsp.getWriter().println(wrapperContent);
	   		return;
		}
		if(url.equals("/sitemap.xml"))
		{
			file = "/sitemap.jsp";
			
			String redirectURL = rsp.encodeRedirectURL(file);
	   		
	   		RequestDispatcher dispatcher = req.getRequestDispatcher(redirectURL);
	   		BufferedHttpResponseWrapper wrapper = new BufferedHttpResponseWrapper(rsp);
	   		
	   		dispatcher.include(request, wrapper);
	   		String wrapperContent = new String(wrapper.getOutput());
	   		rsp.setContentType("text/xml");
	   		rsp.getWriter().println(wrapperContent);
	   		return;
		}
		MessageDigest message = null;
		try {
			message = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		message.update(url.getBytes(), 0, url.length());
		String md5URL = new BigInteger(1, message.digest()).toString(16);
	
		String cachedFile = md5URL + ".htm";
		
		try {
			ObjectifyService.register(model.Map.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		Objectify objectify = ObjectifyService.begin();
		
		try {
			model.Map map = objectify.get(new Key<model.Map>(model.Map.class, cachedFile));
			try {
				System.out.println("co file");
				
				rsp.getWriter().println(File.Read(map.getBlodKey()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			
			String redirectURL = rsp.encodeRedirectURL(file);
	   		
	   		RequestDispatcher dispatcher = req.getRequestDispatcher(redirectURL);
	   		BufferedHttpResponseWrapper wrapper = new BufferedHttpResponseWrapper(rsp);
	   		
	   		dispatcher.include(request, wrapper);
	   		String wrapperContent = new String(wrapper.getOutput());
			
	   		if(!wrapperContent.equals("error"))
	   		{
				model.Map maps = new model.Map();
				maps.setUrl(cachedFile);
				maps.setBlodKey(File.Create(wrapperContent));
				
				objectify.put(maps);
				rsp.getWriter().println(File.Read(maps.getBlodKey()));
	   		} else {
	   			System.out.println("error");
	   			redirectURL = rsp.encodeRedirectURL("/404error.jsp");
	   			dispatcher = req.getRequestDispatcher(redirectURL);
		   		wrapper = new BufferedHttpResponseWrapper(rsp);
		   		dispatcher.include(request, wrapper);
		   		wrapperContent = new String(wrapper.getOutput());
		   		rsp.setStatus(404);
		   		rsp.getWriter().println(wrapperContent);
	   		}
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
